﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


using System.Net;
using System.Net.Sockets;
using System.Threading;
using AllInOne.Common;
using Org.BouncyCastle.Utilities.Encoders;

namespace AllInOne.MainPages
{
    /// <summary>
    /// winTest_SM3.xaml 的交互逻辑
    /// </summary>
    public partial class WinTest_SM2 : Window
    {
        public WinTest_SM2()
        {
            InitializeComponent();

            //需要说明的是：每次生成的密文都不一样
            tb_content.Text = "ererfeiisgod";
            //为了测方便：--秘钥写固定
            tb_publicKey.Text = "04F6E0C3345AE42B51E06BF50B98834988D54EBC7460FE135A48171BC0629EAE205EEDE253A530608178A98F1E19BB737302813BA39ED3FA3C51639D7A20C7391A";
            tb_privateKey.Text = "3690655E33D5EA3D9A4AE1A1ADD766FDEA045CDEAA43A9206FB8C430CEFE0D94";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //生成秘钥
            //SM2Utils.GenerateKeyPair();
            
            String plainText = "ererfeiisgod";
            byte[] sourceData = Encoding.UTF8.GetBytes(plainText);

            string str = "";
            for (int i = 0; i < sourceData.Length; i++)
            {
                str += sourceData[i].ToString("X2");
            }
            System.Console.Out.WriteLine("加密前原文本字节数据: " + str);
            //下面的秘钥可以使用generateKeyPair()生成的秘钥内容  
            // 国密规范正式私钥  
            //String prik = "3690655E33D5EA3D9A4AE1A1ADD766FDEA045CDEAA43A9206FB8C430CEFE0D94";
            //// 国密规范正式公钥  
            //String pubk = "04F6E0C3345AE42B51E06BF50B98834988D54EBC7460FE135A48171BC0629EAE205EEDE253A530608178A98F1E19BB737302813BA39ED3FA3C51639D7A20C7391A";
            // 国密规范正式私钥
            String prik = "00BC73D0B52B6856217FF7DD82008BCE6BD14FAD9339D2CC9F078AD9E6E72AFCCD";
            // 国密规范正式公钥  
            String pubk = "048700970482569577E8FD08AB5B177364670A4FB78265307533E40F10DFEE67C658DEBEAE1D2E9DC89D109EC42A1487A1A97338AD2A08C7B28F73155757ED890C";


            System.Console.Out.WriteLine("加密: ");
            String cipherText = SM2Utils.Encrypt(Hex.Decode(pubk), sourceData);
            System.Console.Out.WriteLine(cipherText);

            System.Console.Out.WriteLine("解密: ");
            byte[] result= SM2Utils.Decrypt(Hex.Decode(prik), Hex.Decode(cipherText));
            str = "";
            for (int i = 0; i < result.Length; i++)
            {
                str += result[i].ToString("X2");
            }
            if (str== "4E2932BBA763662E0FDAC728")
            {
                MessageBox.Show("加密正确");
            }

            plainText = Encoding.Default.GetString(result);
            System.Console.Out.WriteLine("解密后字节数据: " + str);
            System.Console.Out.WriteLine(plainText);

            Console.ReadLine();

            ////测试01--SM3签名
            //if (tb_data.Text == null || tb_data.Text == "")
            //{
            //    MessageBox.Show("请输入要SM3签名的字符串");
            //    return;
            //}
            //string sm3 = GetSM3("hello hyperchain");
            //tb_sm3.Text = sm3;

            ////测试02--时间格式
            //string strDt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            //MessageBox.Show(strDt);

            //////测试03--是否可以修改request.Headers
            //try
            //{
            //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("https://192.168.41.41:8090/api/v1/equipmentCert/upload"));
            //    RequsetHeaders(request, "string sysCode", "string distCode", "string dataAuth");

            //    if (request.Headers.Count != 0)
            //    {
            //        MessageBox.Show(request.Headers["sysCode"].ToString());
            //    }
            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}
        }

        public static void RequsetHeaders(HttpWebRequest request, string sysCode, string distCode, string dataAuth)
        {
            request.Method = "POST";
            request.ContentType = "application/json";

            #region 请求头
            //必填--HTTP请求方法
            request.Headers.Add("RequestMethod", "POST");
            //必填--系统代码
            request.Headers.Add("sysCode", sysCode);
            //必填--行政区划代码
            request.Headers.Add("distCode", distCode);
            ////必填--数据SM3摘要，用于数据完整性校验
            //request.Headers.Add("dataSM3", "");
            //必填--鉴权码
            request.Headers.Add("dataAuth", dataAuth);
            //非必填--选填 Content中传输数据的格式(JSON)
            request.Headers.Add("dataFormat", "JSON");
            #endregion
        }

        /// <summary>
        /// 获取SM3签名字符串
        /// </summary>
        /// <param name="data">待计算的数据UTF-8数据字符串</param>
        /// <returns></returns>
        private string GetSM3(string data)
        {
            byte[] md = new byte[32];
            byte[] msg1 = Encoding.UTF8.GetBytes(data);
            SM3Digest sm3 = new SM3Digest();
            sm3.BlockUpdate(msg1, 0, msg1.Length);
            sm3.DoFinal(md, 0);
            string str = "";
            for (int i = 0; i < md.Count(); i++)
            {
                str += md[i].ToString("x2");
            }
            return str;
        }

        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            try
            {
                String plainText = tb_content.Text;
                byte[] sourceData = Encoding.UTF8.GetBytes(plainText);

                //加密前原文本字节数据
                string str = "";
                for (int i = 0; i < sourceData.Length; i++)
                {
                    str += sourceData[i].ToString("X2");
                }
                System.Console.Out.WriteLine("加密前原文本字节数据: " + str);
                tb_result2.Text = "加密前原文本字节数据: " + str;

                System.Console.Out.WriteLine("加密: ");
                String cipherText = SM2Utils.Encrypt(Hex.Decode(tb_publicKey.Text), sourceData);
                tb_result.Text = cipherText;
                System.Console.Out.WriteLine(tb_result.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Console.Out.WriteLine("解密: ");
                byte[] result = SM2Utils.Decrypt(Hex.Decode(tb_privateKey.Text), Hex.Decode(tb_content.Text));
                //将字节数据转成utf8
                tb_result.Text = Encoding.UTF8.GetString(result);
                System.Console.Out.WriteLine(tb_result.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
